// 旋钮交互逻辑
class KnobController {
    constructor(knobElement, valueElement) {
        this.knob = knobElement;
        this.indicator = knobElement.querySelector('.knob-indicator');
        this.valueElement = valueElement;
        this.isDragging = false;
        this.currentRotation = 0;

        this.bindEvents();
    }

    bindEvents() {
        // 改进鼠标事件处理
        this.knob.addEventListener('mousedown', (e) => {
            e.preventDefault();
            this.isDragging = true;
            const rect = this.knob.getBoundingClientRect();
            this.centerX = rect.left + rect.width / 2;
            this.centerY = rect.top + rect.height / 2;
            this.startAngle = this.currentRotation;
        });

        document.addEventListener('mousemove', (e) => {
            if (this.isDragging) {
                const offsetX = e.clientX - this.centerX;
                const offsetY = this.centerY - e.clientY;
                
                // 使用极坐标计算旋转角度
                let angle = Math.atan2(offsetY, offsetX) * (180 / Math.PI);
                angle = (angle + 90 + 360) % 360;

                // 计算角度差并应用平滑旋转
                const angleDiff = angle - this.startAngle;
                const smoothFactor = 0.2;
                const deltaAngle = angle - this.startAngle;
                this.currentRotation = Math.min(270, Math.max(-90, this.currentRotation + deltaAngle * smoothFactor));
                this.startAngle = angle;

                // 更新指针位置
                const rect = this.knob.getBoundingClientRect();
                const radius = rect.width / 2;
                const radians = this.currentRotation * (Math.PI / 180);
                const edgeX = rect.left + rect.width / 2 + Math.cos(radians) * radius;
                const edgeY = rect.top + rect.height / 2 - Math.sin(radians) * radius;
                this.indicator.style.left = `${edgeX - rect.left}px`;
                this.indicator.style.top = `${edgeY - rect.top}px`;
                this.updateRotation();
            }
        });

        document.addEventListener('mouseup', () => {
            this.isDragging = false;
        });
    }

    updateRotation() {
        this.indicator.style.transform = `translateX(-50%) rotate(${this.currentRotation}deg)`;
        const normalizedValue = this.currentRotation / 360;
        this.valueElement.textContent = normalizedValue.toFixed(2);
    }
}

// 初始化旋钮
const freqKnob = new KnobController(
    document.querySelector('.knob-container:first-child .knob'),
    document.getElementById('freq-value')
);

const modKnob = new KnobController(
    document.querySelector('.knob-container:nth-child(2) .knob'),
    document.getElementById('mod-value')
);